﻿#region Copyright (c) 2003 - 2008, Andreas Mueller
/////////////////////////////////////////////////////////////////////////////////////////
// 
// Copyright (c) 2003 - 2008, Andreas Mueller.
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// Contributors:
//    Andreas Mueller - initial API and implementation
//
// 
// This software is derived from software bearing the following
// restrictions:
// 
// Copyright (c) 1994
// Hewlett-Packard Company
// 
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation.  Hewlett-Packard Company makes no
// representations about the suitability of this software for any
// purpose.  It is provided "as is" without express or implied warranty.
// 
// 
// Copyright (c) 1996,1997
// Silicon Graphics Computer Systems, Inc.
// 
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation.  Silicon Graphics makes no
// representations about the suitability of this software for any
// purpose.  It is provided "as is" without express or implied warranty.
// 
// 
// (C) Copyright Nicolai M. Josuttis 1999.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
// 
/////////////////////////////////////////////////////////////////////////////////////////
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using Rhino.Mocks;

namespace NStl.NUnit.AlgorithmFixtures.TopologicalSort
{
    [TestFixture]
    public class TopologicalSortSupportFixture
    {
        private static MockRepository mockRepository;
        [SetUp]
        public void SetUp()
        {
            mockRepository = new MockRepository();
        }
        [TearDown]
        public void TearDown()
        {
            mockRepository.VerifyAll();
        }

        [Test]
        public void IsSorted()
        {
            IGraphNode a = mockRepository.Stub<IGraphNode>();
            IGraphNode b = mockRepository.Stub<IGraphNode>();
            IGraphNode c = mockRepository.Stub<IGraphNode>();

            using (mockRepository.Record())
            {
                Expect.Call(a.Parents).Return(new IGraphNode[] { }).Repeat.Any();
                Expect.Call(b.Parents).Return(new[] { a }).Repeat.Any();
                Expect.Call(c.Parents).Return(new[] { a }).Repeat.Any();
            }

            IEnumerable<IGraphNode> graph = new[] { a, b, c };

            bool isSorted = IsTopologicallySorted(graph, node => node.Parents);
            Assert.That(isSorted, Iz.True);
        }

        [Test]
        public void IsNotSorted()
        {
            IGraphNode a = mockRepository.Stub<IGraphNode>();
            IGraphNode b = mockRepository.Stub<IGraphNode>();
            IGraphNode c = mockRepository.Stub<IGraphNode>();

            using (mockRepository.Record())
            {
                Expect.Call(a.Parents).Return(new IGraphNode[] { }).Repeat.Any();
                Expect.Call(b.Parents).Return(new[] { a }).Repeat.Any();
                Expect.Call(c.Parents).Return(new[] { a }).Repeat.Any();
            }

            IEnumerable<IGraphNode> graph = new[] { c, b, a };
            bool isSorted = IsTopologicallySorted(graph, node => node.Parents);
            Assert.That(isSorted, Iz.False);
        }
        public static bool IsTopologicallySorted<GraphNode>(IEnumerable<GraphNode> graph, Func<GraphNode, IEnumerable<GraphNode>> predecessors)
        {
            List<GraphNode> theGraph = new List<GraphNode>(graph);
            if (theGraph.Count <= 1)
                throw new ArgumentException("The graph has less than two nodes!!");


            for (int i = 1; i < theGraph.Count; ++i)
            {
                GraphNode node = theGraph[i];
                IEnumerable<GraphNode> superSet = theGraph.Take(i);
                IEnumerable<GraphNode> subSet = UniquePredecessorsRecursively(node, predecessors);


                if (!subSet.Intersect(superSet).Any())
                    return false;
            }
            return true;
        }

        private static IEnumerable<GraphNode> UniquePredecessorsRecursively<GraphNode>(GraphNode graphNode, Func<GraphNode, IEnumerable<GraphNode>> predecessors)
        {
            HashSet<GraphNode> collectedUniquePredecessors = new HashSet<GraphNode>();
            CollectPredecessorsRecursively(graphNode, predecessors, collectedUniquePredecessors);
            return collectedUniquePredecessors;
        }


        private static void CollectPredecessorsRecursively<GraphNode>(GraphNode graphNode, Func<GraphNode, IEnumerable<GraphNode>> predecessorAccsessor, ICollection<GraphNode> predecessors)
        {
            foreach (GraphNode node in predecessorAccsessor(graphNode))
            {
                CollectPredecessorsRecursively(node, predecessorAccsessor, predecessors);
                predecessors.Add(node);
            }
        }
    }

    public interface IGraphNode
    {
        IList<IGraphNode> Parents { get; }
    }
}